import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import numpy as np
from uilt.in_data import *
from model import *

Loss = []
Adv_Loss = []
task_acc = []
id_acc = []
epochs = []
def train_dagn(model, dataloader, optimizer, optimizer_attention, device, lambda_dec=0.1, num_epochs=50):
    criterion = nn.CrossEntropyLoss()
    model.train()
    for epoch in range(num_epochs):
        for batch in dataloader:
            x = batch['x'].to(device)
            y_id = batch['y_id'].to(device)
            y_task = batch['y_task'].to(device)
            print(f"Input x shape: {x.shape}, y_id shape: {y_id.shape}, y_task shape: {y_task.shape}")
            # --------- 第1阶段：前向传播 + 更新主网络 ----------
            optimizer.zero_grad()
            out_id, out_aux, out_task, fID, fT, alpha = model(x)

            loss_id = criterion(out_id, y_id)
            loss_aux = criterion(out_aux, y_id)
            loss_task = criterion(out_task, y_task)
            f_concat = torch.cat([fID, fT], dim=1)
            loss_dec = feature_decorrelation_loss(f_concat)

            loss = loss_id + loss_aux + loss_task + lambda_dec * loss_dec
            loss.backward()
            optimizer.step()

            # 计算身份识别准确率
            _, pred_id = torch.max(out_id, dim=1)
            acc_id = (pred_id == y_id).float().mean()

            # 计算任务识别准确率
            _, pred_task = torch.max(out_task, dim=1)
            acc_task = (pred_task == y_task).float().mean()

            # --------- 第2阶段：对抗注意力更新 ----------
            for param in model.id_classifier.parameters():
                param.requires_grad = False
            for param in model.aux_id_clf.parameters():  # 修改了这里
                param.requires_grad = False

            optimizer_attention.zero_grad()
            _, out_aux_adv, _, _, _, _ = model(x)
            entropy = -torch.mean(torch.sum(F.softmax(out_aux_adv, dim=1) * F.log_softmax(out_aux_adv, dim=1), dim=1))
            adv_loss = entropy
            adv_loss.backward()
            optimizer_attention.step()

            for param in model.id_classifier.parameters():
                param.requires_grad = True
            for param in model.aux_id_clf.parameters():  # 修改了这里
                param.requires_grad = True
            print(f"Epoch [{epoch + 1}/{num_epochs}], "
                  f"Loss: {loss.item():.4f}, "
                  f"Adv Loss: {adv_loss.item():.4f}, "
                  f"ID Acc: {acc_id.item()*100:.2f}%, "
                  f"Task Acc: {acc_task.item()*100:.2f}%")
            Loss.append(loss.item())
            Adv_Loss.append(adv_loss.item())
            id_acc.append(acc_id.item())
            epochs.append(epoch + 1)
            task_acc.append(acc_task.item())


if __name__ == "__main__":
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    # 超参数设置
    # 设置模型的超参数
    in_channels = 64  # 输入通道数：PSD特征是单通道
    t = 24  # 时间步数：每个样本包含24个时间片
    s1 = 32  # Block_S 中用于低频的卷积核大小
    s2 = 32  # Block_S 中用于高频的卷积核大小
    s = 32  # Block_S 中用于其他频段的卷积核大小
    num_eeg_channels = 16  # EEG通道数，通常为10–20系统中的有效通道数量
    num_id_classes = 19  # 身份类别数
    num_task_classes = 2  # 任务类别数
    att_hidden_dim = 32  # 注意力模块的隐藏层维度
    att_temp = 0.5  # Gumbel-Softmax温度参数，用于控制注意力分布的离散程度
    model = DAGN(in_channels, t, s1, s2, s,
                 num_id_classes, num_task_classes, att_hidden_dim, att_temp)
    model.to(device)
    # 主体优化器：更新所有模型参数（包括分类器和注意力模块）
    optimizer = optim.Adam(model.parameters(), lr=0.0001)
    # 注意力模块单独的优化器，用于对抗自挑战训练阶段
    optimizer_attention = optim.SGD(model.attention.parameters(), lr=0.005, momentum=0.9)
    # 使用自定义数据加载器加载 PSD 特征数据及对应标签
    data, identity, task = M109_dataloader(num_id_classes)
    # 创建数据集对象，封装数据与标签
    dataset = RealEEGDataset(data, identity, task)
    # 用 PyTorch 的 DataLoader 创建迭代器，支持批处理和随机打乱
    dataloader = DataLoader(dataset, batch_size=64, shuffle=True)
    # 使用 feature decorrelation + 对抗注意力学习
    # lambda_dec=0.1 控制 decorrelation 损失的权重，num_epochs=5 表示训练5个周期
    train_dagn(model, dataloader, optimizer, optimizer_attention, device, lambda_dec=0.1, num_epochs=80)




